package UDP.EchoServer2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 服务端
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);// 指定服务器的端口号
    }
    // start方法,接受用户的请求
    public void start() throws IOException {
        while (true) {

            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);// 接受用户传来的数据

            System.out.printf("[ip: %s port: %s \n",requestPacket.getAddress().toString(),requestPacket.getPort());

            // 把得到的对象解析成一个字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            // 作出响应
            String response = process(request);

            // 打包成一个数据报,返回 --- 指定返回给谁
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {

        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }

}
